import React, { useState } from 'react';
import { Button, Input, message, Table, Tag, Upload } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Modal, Form, DatePicker, Select, TimePicker } from 'antd';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';
import { ColumnType } from 'antd/es/table';

// 定义课程表数据结构
export interface CourseData {
    id: number;
    date: string;        // 周几（周一到周日）
    content: string;     // 内容
    time: string;        // 时间
    personnel: string;   // 人员
}

// 星期几的选项
const weekOptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

// 示例数据
const sampleData: CourseData[] = [
    {
        id: 1,
        date: '周一',
        content: '团队管理基础培训',
        time: '09:00-11:00',
        personnel: '王建明, 李海燕'
    },
    {
        id: 2,
        date: '周二',
        content: '项目规划与执行',
        time: '14:00-16:00',
        personnel: '张卫国, 陈晓峰, 周婷婷'
    },
    {
        id: 3,
        date: '周三',
        content: '技术创新研讨会',
        time: '10:00-12:00',
        personnel: '赵志强, 孙建国'
    },
    {
        id: 4,
        date: '周四',
        content: '绩效评估方法',
        time: '13:30-15:30',
        personnel: '徐志伟, 林雪'
    },
    {
        id: 5,
        date: '周五',
        content: '年度计划制定',
        time: '09:30-11:30',
        personnel: '王建明, 张卫国'
    },
    {
        id: 6,
        date: '周六',
        content: '企业文化建设',
        time: '14:30-16:30',
        personnel: '黄美玲, 林雪'
    },
    {
        id: 7,
        date: '周日',
        content: '财务管理与预算',
        time: '10:30-12:30',
        personnel: '黄美玲'
    },
    {
        id: 8,
        date: '周一',
        content: '市场营销策略',
        time: '15:00-17:00',
        personnel: '徐志伟, 赵志强'
    },
    {
        id: 9,
        date: '周二',
        content: '客户服务标准',
        time: '09:00-11:00',
        personnel: '李海燕, 周婷婷'
    },
    {
        id: 10,
        date: '周三',
        content: '年终总结与展望',
        time: '14:00-16:00',
        personnel: '王建明, 张卫国, 孙建国'
    }
];

const Officer: React.FC = () => {
    const [courseData, setCourseData] = useState<CourseData[]>(sampleData);
    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState<CourseData | null>(null);
    const [searchValue, setSearchValue] = useState('');

    // 搜索功能
    const filteredData = courseData.filter(item =>
        item.content.toLowerCase().includes(searchValue.toLowerCase()) ||
        item.personnel.toLowerCase().includes(searchValue.toLowerCase())
    );

    // 表格列配置
    const columns: ColumnType<CourseData>[] = [
        {
            title: '日期',
            dataIndex: 'date',
            width: 100,
            filters: weekOptions.map(week => ({ text: week, value: week })),
            onFilter: (value: any, record: CourseData) => record.date === value,
            sorter: (a: CourseData, b: CourseData) => {
                // 对周几进行排序
                const weekOrder = { '周一': 1, '周二': 2, '周三': 3, '周四': 4, '周五': 5, '周六': 6, '周日': 7 };
                return weekOrder[a.date as keyof typeof weekOrder] - weekOrder[b.date as keyof typeof weekOrder];
            }
        },
        {
            title: '内容',
            dataIndex: 'content',
            width: 200,
        },
        {
            title: '时间',
            dataIndex: 'time',
            width: 120,
        },
        {
            title: '人员',
            dataIndex: 'personnel',
            width: 200,
            render: (text: string) => (
                <div>
                    {text.split(',').map((name, index) => (
                        <Tag key={index} color="blue" className="m-1">
                            {name.trim()}
                        </Tag>
                    ))}
                </div>
            )
        },
        {
            title: '操作',
            width: 120,
            render: (_: any, record: CourseData) => (
                <div className="flex space-x-2">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        className="text-blue-500 hover:text-blue-700"
                        onClick={() => {
                            setCurrentRecord(record);
                            form.setFieldsValue({
                                ...record,
                                date: record.date,
                            });
                            setIsModalVisible(true);
                        }}
                    />
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => {
                            setCourseData(courseData.filter(d => d.id !== record.id));
                            message.success('删除成功！');
                        }}
                    />
                </div>
            )
        }
    ];

    // 表单提交处理
    const handleFormSubmit = async () => {
        try {
            const values = await form.validateFields();
            const processedValues = {
                ...values,
                time: `${values.startTime.format('HH:mm')}-${values.endTime.format('HH:mm')}`,
            };
            delete processedValues.startTime;
            delete processedValues.endTime;

            setCourseData(prev => {
                if (currentRecord) {
                    // 编辑现有记录
                    message.success('修改成功！');
                    return prev.map(item =>
                        item.id === currentRecord.id ? { ...item, ...processedValues } : item
                    );
                } else {
                    // 新增记录
                    message.success('新增成功！');
                    return [...prev, {
                        ...processedValues,
                        id: Math.max(0, ...prev.map(p => p.id)) + 1
                    }];
                }
            });
            setIsModalVisible(false);
            form.resetFields();
        } catch (error) {
            message.error('验证失败: 请检查所有必填项');
        }
    };
    // 处理导出Excel
    const handleExportExcel = () => {
        try {
            // 从columns配置中获取需要导出的字段配置
            const exportColumns = columns
                .filter(col => col.dataIndex && col.title !== '操作')
                .map(col => ({
                    title: col.title as string,
                    dataIndex: col.dataIndex as string
                }));
            // 准备导出数据
            const exportData = courseData.map(record => {
                const rowData: Record<string, any> = {};
                exportColumns.forEach(col => {
                    let value = record[col.dataIndex as keyof typeof record];

                    rowData[col.title] = value;
                });
                return rowData;
            });
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(exportData);
            // 设置列宽
            const colWidths = exportColumns.map(() => ({ wch: 15 }));
            ws['!cols'] = colWidths;
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, '课程安排表');
            // 导出Excel文件
            XLSX.writeFile(wb, `课程安排表_${dayjs().format('YYYY-MM-DD')}.xlsx`);
            message.success('导出成功！');
        } catch (error) {
            message.error('导出失败，请重试！');
            console.error('导出错误：', error);
        }
    };
    // 处理导入Excel
    const handleImportExcel = (file: File) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target?.result as ArrayBuffer);
                const workbook = XLSX.read(data, { type: 'array' });
                const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(worksheet);

                // 处理导入的数据
                const importedData: CourseData[] = jsonData.map((row: any, index) => ({
                    id: Math.max(0, ...courseData.map(p => p.id)) + index + 1,
                    date: row['日期'] || '周一',
                    content: row['内容'] || '',
                    time: row['时间'] || '',
                    personnel: row['人员'] || ''
                }));

                // 更新数据
                setCourseData(prev => [...prev, ...importedData]);
                message.success(`成功导入 ${importedData.length} 条数据setSearchValue`);
            } catch (error) {
                message.error('导入失败，请检查文件格式是否正确');
                console.error('导入错误：', error);
            }
        };
        reader.readAsArrayBuffer(file);
        return false;
    };

    // 初始化时间值
    const initializeTimeValues = () => {
        if (currentRecord && currentRecord.time) {
            const [start, end] = currentRecord.time.split('-');
            return {
                startTime: dayjs(start, 'HH:mm'),
                endTime: dayjs(end, 'HH:mm')
            };
        }
        return {
            startTime: dayjs('09:00', 'HH:mm'),
            endTime: dayjs('11:00', 'HH:mm')
        };
    };

    // 当编辑模态框显示时设置时间字段
    React.useEffect(() => {
        if (isModalVisible && currentRecord) {
            const { startTime, endTime } = initializeTimeValues();
            form.setFieldsValue({
                startTime,
                endTime
            });
        }
    }, [isModalVisible, currentRecord, form]);

    return (
        <div className="p-6 bg-white rounded-lg shadow-sm">
            <div className="mb-6 flex justify-between items-center">
                <h2 className="text-2xl font-semibold text-gray-800 min-w-[200px]">课程安排表</h2>
                <Input.Search
                    placeholder="根据内容或人员搜索"
                    className="w-full md:w-64 rounded-lg border-gray-300"
                    onChange={e => setSearchValue(e.target.value)}
                    onSearch={value => setSearchValue(value)}
                />
                <Upload
                    accept=".xlsx,.xls"
                    showUploadList={false}
                    beforeUpload={(file) => {
                        handleImportExcel(file);
                        return false;
                    }}
                >
                    <Button
                        type="primary"
                        className="bg-green-600 hover:bg-green-700 h-10 px-6 flex items-center w-full md:w-auto mr-2"
                    >
                        导入Excel
                    </Button>
                </Upload>
                <Button
                    type="primary"
                    className="bg-blue-600 hover:bg-blue-700 h-10 px-6 flex items-center w-full md:w-auto mr-2"
                    onClick={handleExportExcel}
                >
                    导出Excel
                </Button>
                <Button
                    type="primary"
                    className="bg-blue-600 hover:bg-blue-700 h-10 px-6 flex items-center w-full md:w-auto"
                    onClick={() => {
                        setCurrentRecord(null);
                        form.resetFields();
                        form.setFieldsValue(initializeTimeValues());
                        setIsModalVisible(true);
                    }}
                >
                    + 添加课程
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={filteredData.map(item => ({ ...item, key: item.id }))}
                pagination={{ pageSize: 8 }}
                bordered
                scroll={{ x: 1000 }}
                rowClassName="hover:bg-gray-50 transition-colors"
                className="rounded-lg overflow-hidden border border-gray-200"
            />

            {/* 添加/编辑模态框 */}
            <Modal
                title={currentRecord ? "编辑课程信息" : "新增课程"}
                open={isModalVisible}
                onOk={handleFormSubmit}
                onCancel={() => setIsModalVisible(false)}
                cancelText="取消"
                okText="提交"
            >
                <Form form={form} layout="vertical">
                    <Form.Item label="日期" name="date" rules={[{ required: true, message: '请选择日期' }]}>
                        <Select>
                            {weekOptions.map(week => (
                                <Select.Option key={week} value={week}>{week}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="内容" name="content" rules={[{ required: true, message: '请输入课程内容' }]}>
                        <Input.TextArea rows={3} />
                    </Form.Item>
                    <div className="flex gap-4">
                        <Form.Item label="开始时间" name="startTime" rules={[{ required: true, message: '请选择开始时间' }]} className="flex-1">
                            <TimePicker format="HH:mm" className="w-full" />
                        </Form.Item>
                        <Form.Item label="结束时间" name="endTime" rules={[{ required: true, message: '请选择结束时间' }]} className="flex-1">
                            <TimePicker format="HH:mm" className="w-full" />
                        </Form.Item>
                    </div>
                    <Form.Item label="参与人员" name="personnel" rules={[{ required: true, message: '请输入参与人员' }]}>
                        <Input placeholder="多个人员请用逗号分隔" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Officer;